<template>
    <el-button type="write" @click="ExportToExcel">导出</el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="saleDate" label="销售日期" width="120">
            <template #default="scope">
                {{ formatDate(scope.row.saleDate) }}
            </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="productName" label="产品名称" width="120" />
        <el-table-column prop="saleSum" label="销售数量" width="120" />
        <el-table-column prop="salePrice" label="销售单价" width="120" />
        <el-table-column prop="sales" label="销售额" width="120" />
        <el-table-column prop="salespeople" label="销售人员" width="120" />
        <el-table-column prop="salesChannels" label="销售渠道" width="120" />
        <el-table-column prop="paymentMethods" label="付款方式" width="120" />
        <el-table-column prop="remark" label="备注" width="120" />
        <el-table-column fixed="right" label="操作" min-width="140">
            <template #default="scoped">
                <el-button link type="danger" :icon="Delete" size="small" @click="Del(scoped.row.saleId)">删除</el-button>
                <el-button link type="warning" :icon="Edit" size="small" @click="Upd(scoped.row.saleId)">修改</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
        :page-sizes="[15, 20, 25, 30]" layout="total, sizes, prev, pager, next, jumper" :total="form.totalCount"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'
import {read,write} from '@/axios/axiosHelper'

const router = useRouter()
const route = useRoute()

const tableData = ref([]);

const form = reactive({
    pageIndex: 1,
    pageSize: 15,
    totalCount: 0,
    totalPage: 0,
})

const handleSizeChange = (val: number) => {
    Show();
}
const handleCurrentChange = (val: number) => {
    Show();
}

onMounted(() => {
    Show();
})

const Show = () => {
    read.get("/f-read/api/Sale/QuerySale", {
        params: {
            pageIndex: form.pageIndex,
            pageSize: form.pageSize,
        }
    })
        .then(res => {
            tableData.value = res.data.data;
            form.totalCount = res.data.totalCount;
            form.totalPage = res.data.totalPage;
        })
}

const formatDate = (date: string) => {
    return moment(date).format('YYYY-MM-DD');
}

const Del = (saleId: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            write.post("/f-write/api/Sale/DelSale", {
                saleId: saleId
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success("删除成功");
                        Show();
                    }
                    else {
                        ElMessage.error("删除失败");
                        return;
                    }
                })
        })
}

const Upd = (saleId: any) => {
    router.push({
        path: '/UpdSales',
        query: {
            saleId: saleId
        }
    })
}

// 修改后的导出方法
const ExportToExcel = async () => {
  try {
    const res = await axios.get("https://localhost:7238/api/Sale/ExportToExcel", {
      responseType: 'blob' // 设置响应类型为 blob
    });
    // 创建一个临时的 URL 对象
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    // 设置下载的文件名
    link.setAttribute('download', 'production_orders.xlsx');
    document.body.appendChild(link);
    link.click();
    // 释放 URL 对象
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`导出数据出错，状态码: ${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('导出数据出错，无响应，请检查网络');
      } else {
        ElMessage.error('导出数据出错，请求配置有误');
      }
    } else {
      ElMessage.error('导出数据出错，请检查网络或联系管理员');
    }
    console.error('导出数据出错:', error);
  }
};

</script>